package com.daoImpl;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;

import com.bean.User;
import com.dao.LoginDao;

public class LoginDaoImpl implements LoginDao {

	User user;

	// hibernate读取对象所定义的对象
	private static final String CFG_FILE_LOCATION = "/Hibernate.cfg.xml";
	Configuration cfg;
	StandardServiceRegistryBuilder serviceRegistry;
	SessionFactory sessionFactory;
	Session session;
	Transaction ts;

	@SuppressWarnings("unchecked")
	public User getUser(String username) {
		user = new User();

		// 用hibernate从数据库获取user
		// cfg = = new
		// StandardServiceRegistryBuilder().configure("Hibernate.cfg.xml").build();
		// 5.*以前用ServiceRegistryBuilder
		// 5.*以后用StandardServiceRegistryBuilder
		final StandardServiceRegistry registry = new StandardServiceRegistryBuilder().configure("Hibernate.cfg.xml")
				.build();
		// 2. 根据服务注册类创建一个元数据资源集，同时构建元数据并生成应用一般唯一的的session工厂
		SessionFactory sessionFactory = new MetadataSources(registry).buildMetadata().buildSessionFactory();

		/**** 上面是配置准备，下面开始我们的数据库操作 ******/
		Session session = sessionFactory.openSession();// 从会话工厂获取一个session
		ts = session.beginTransaction();

		// hql查询
		String hql = "from User";
		@SuppressWarnings({ "rawtypes" })
		List result = session.createQuery(hql).getResultList();
		for (User user2 : (List<User>) result) {
			if (username.equals(user2.getUsername())) {
				user.setUsername(user2.getUsername());
				user.setPassword(user2.getPassword());
			}
		}

		// 测试用
		System.out.println("可以连接数据库");
		ts.commit();
		session.close();

		if (user.getUsername() != null) {
			return user;
		} else {
			return new User();
		}
	}

}
